// page cart, order and pay
(function(Yo, YoPages){
	var Section = Yo.Section;
	var Req = Yo.Req;
	var Pager = Yo.Pager;

	var Cart = function(){};
	Cart.prototype.save = function(){
		var ll = $('#cart-content').find('.option-input:checked').map(function(){
			var ch = $(this);
			var item = ch.closest('li');

			var id = item.attr('data-item-id');
			// 单价
			var price = +item.attr('data-item-price');
			// 数量
			var qt = +item.find('.qt').val();

			var title = item.find('.cart-info').find('h4').text();

			return {id: id, price: price, qt: qt || 1, title: title};
		}).get();	
		
		this.ll = ll;
	};

	Cart.prototype.render = function(){
		if(!this.ll){
			$('#cart-item-list').html('');
			return;
		}

		var tpl = $('#tplCartItemList').html();
		var html = Yo.format(tpl, {ll: this.ll});
		$('#cart-item-list').html(html);
	};

	Cart.prototype.isEmpty = function(){
		return !this.ll || !this.ll.length;
	};

	Cart.prototype.clear = function(){
		if(this.ll)
			this.ll.splice(0, this.ll.length);
	};

	Cart.prototype.add = function(item){
		if(!this.ll){
			this.ll = [];
		}

		var one = _.findWhere(this.ll, {id: '' + item.id});
		if(one){
			one.qt++;
		}else{
			var added = {qt: 1, id: '' + item.id, title: item.title, des: item.des, 
				price: item.price, priceOld: item.priceOld};
			this.ll.push(added);
		}
	};

	Cart.prototype.getTotalPrice = function(){
		if(!this.ll)
			return 0;

		var totalPrice = 0;
		_.each(this.ll, function(it){
			totalPrice += it.price * it.qt;
		});
		return totalPrice;
	};

	// cart
	YoPages.initPages.push(function(){
		Section.cart = new Cart();

		$('#btnAddToCart,#btnAddToOrder').click(function(e){
			var item = Section.items.get(Section.currentItemId);
			if(!item){
				Yo.log.i('no way');
				return;
			}

			// 立即购买
			if(e.target.id == 'btnAddToOrder'){
				Section.cart.clear();
				Section.cart.add(JSON.parse(item.objJson));
				Section.go('cart', null, {buyImmediately: true});
			}else{
				Section.cart.add(JSON.parse(item.objJson));
				Section.go('cart');
			}
		});

		$('#linkBack2Home').click(function(){
			Section.hide('cart');
			Section.hide('item-detail');
		});
	});

	var calTotalPrice = function(){
		Section.cart.save();
		$('.order-price-number').text(Section.cart.getTotalPrice());	
	};

	// *** cart
	YoPages.initPages.push(function(){
		$('#cart-content').on('click', '.option-input', function(e){
			calTotalPrice();
		});

		$('#cart-content').on('change', '.qt', function(e){
			calTotalPrice();
		});

		Yo.role('btnDelCartItems').click(function(){
			$('#cart-content').find('.option-input:checked').closest('li').remove();
			calTotalPrice();
		});

		$('#btnSubmitOrder').click(function(){
			if(Section.cart.isEmpty()){
				alert('请先选择购物车的商品！');
				return;
			}

			var params = {};
			params.itemList = Section.cart.ll;

			Req.post('/wx/ind/shop/apply', params, function(data){
				if(data.flag){
					Yo.log.debug(data);
					wx.chooseWXPay({
						timestamp: data.timeStamp, 
						nonceStr: data.nonceStr, 
						package: data.package, 
						signType: data.signType, 
						paySign: data.paySign, 
						success: function (res) {
							Section.go('order-list');
						}
					});
				}else{
					if(data.msg){
						alert(data.msg);
						return;
					}

					if('amount-rangeout' == data.tips){
						alert('金额必须在0-5000之间！');
					}else if('item-list-required' == data.tips){
						alert('请先选择购物车的商品！');
					}else if('wx-order-failed' == data.tips){
						alert('创建微信支付订单失败，请联系客服人员！');
					}
				}
			});
		});

		Section.addPageFn('cart', function(params){
			Section.cart.render();

			if(params && params.buyImmediately){
				$('#btnSubmitOrder').trigger('click');
			}
		});
	});

	// *** order list
	YoPages.initPages.push(function(){
		var pager = new Pager(1, 5, 0);
		pager.init('btnPagePre', 'btnPageNext', function(ll){
			var statusLabels = {
				1: '未支付',
				10: '已经支付'
			};

			_.each(ll, function(it){
				it.dd = moment(it.dd).format('YYYY-MM-DD hh:mm');
				it.statusLabel = statusLabels[it.status];

				it.itemList = JSON.parse(it.detail);
			});

			var tpl = $('#tplOrderItemList').html();
			var html = Yo.format(tpl, {ll: ll});
			$('#order-list-content').html(html);

			$('#labelTotalCount').text('记录数:{0} - {1}/{2}'.format(this.totalCount, 
				this.pageNum, this.getTotalPageNum()));				
		});

		var showInPage = function(ll, pageNum){
			if(ll)
				pager.setList(ll);

			pager.pageNum = pageNum || 1;
			pager.render();
		};

		Section.addPageFn('order-list', function(){
			Req.get('/wx/ind/shop/get-order-list', {}, function(data){
				if(!data.ll)
					return;

				showInPage(data.ll);
			});
		});

		$('#order-list').on('click', '.btn-pay-ag', function(e){
			var li = $(e.target).closest('li');
			var id = li.attr('data-id');
			if(!id)
				return;

			var params = {};
			params.id = id;

			Req.get('/wx/ind/shop/pay-ag', params, function(data){
				if(data.flag){
					Yo.log.debug(data);
					wx.chooseWXPay({
						timestamp: data.timeStamp, 
						nonceStr: data.nonceStr, 
						package: data.package, 
						signType: data.signType, 
						paySign: data.paySign, 
						success: function (res) {
							Section.go('order-list');
						}
					});
				}else{
					if(data.msg){
						alert(data.msg);
						return;
					}

					if('parameter' == data.tips){
						alert('参数错误！');
					}else if('order-not-exists' == data.tips){
						alert('订单错误！');
					}
				}
			});
		});

	});
})(this.Yo, this.YoPages);